package com.huiquan.icd.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.icd.dao.IcdDiseaseSectionRepositoryDao;
import com.huiquan.icd.domain.IcdDiseaseSectionRepository;
import com.huiquan.section.dao.SectionSynonymyDao;

@Service
public class IcdDiseaseSectionRepositoryService extends BaseService {

	@Autowired
	private IcdDiseaseSectionRepositoryDao icdDiseaseSectionRepositoryDao;
	@Autowired
	private SectionSynonymyDao sectionSynonymyDao;
	
	public ModelAndView list(Integer startStr, String keyword, String countPerPageStr, User user, String checkFlag,
			String exactSearchFlag) {
		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		param.put("checkFlag", checkFlag);
		if (StringUtils.isNotBlank(keyword)) {
			param.put("keyword", exactFlag ? keyword : "%" + keyword + "%");
		}
		if ("0".equals(checkFlag)) {
			param.put("order", "a.disease_name ");
		} else {
			param.put("order", "a.gmt_modified desc ");
		}
		int totalSize = icdDiseaseSectionRepositoryDao.retrieveSize(param);
		Map<String, Integer> pageNo;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr + "", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr + "");
		}
		int endPage = pageNo.get("endPage");
		int start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");
		List<IcdDiseaseSectionRepository> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = icdDiseaseSectionRepositoryDao.retrieveList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "疾病名称");

		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("keyword", keyword);

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);
		map.put("check_flag", checkFlag);

		LOGGER.info("Get list end!Params:start={},wordKey={},propertyKey={},type={};total size={}",
				new Object[] { start, totalSize });
		return new ModelAndView("icd/index", map);
	}

//	public ReturnData changeFlag(String id, String flag, User user) {
//
//		icdDiseaseSectionBlackWhiteDao.updateFlag(id, flag, user.getUserId());
//
//		return ReturnUtil.success();
//	}
//
	public ReturnData submitPage(String id, User user) {

		icdDiseaseSectionRepositoryDao.updateSubmit(id.substring(0, id.length() - 1), user.getUserId());

		return ReturnUtil.success();
	}
	public ReturnData changeOptimumSection(String id,String optimumSection,User user) {

		icdDiseaseSectionRepositoryDao.updateOptimumSection(id, optimumSection, user.getUserId());
		
		return ReturnUtil.success();
	}
	
	public ReturnData init() {
		//科室同义词列表
		List<Map<String, String >> synonymyLists = sectionSynonymyDao.retrieveSectionSynonymyRelatList();
		Map<String, String> synonymyMap = new HashMap<>();
		for(Map<String, String > synonymy:synonymyLists){
			synonymyMap.put(synonymy.get("department_name"), synonymy.get("name"));
		}
		//获取所有已校验的疾病名称若已经校验过则不添加未校验
		Map<String, Object> param = new HashMap<>();
		param.put("checkFlag", "1");
		List<IcdDiseaseSectionRepository> list = icdDiseaseSectionRepositoryDao.retrieveList(param);
		List<String> diseaseNames = new ArrayList<>();
		for(IcdDiseaseSectionRepository value :list){
			diseaseNames.add(value.getDiseaseName());
		}
		//获取初始化数据
		List<Map<String, String >> initData = icdDiseaseSectionRepositoryDao.retrieveInitList();
		Set<String> section = new HashSet<String>();
		for(Map<String, String> value: initData){
			section.clear();
			String diseaseName = value.get("icd_name");
			String[] externalSections = value.get("external_section").split("\\s+");
			for(String externalSection:externalSections){
				//如果有同义词经过同义词处理
				if(synonymyMap.get(externalSection) == null){
					section.add(externalSection);
				}else{
					section.add(synonymyMap.get(externalSection));
				}
			}
			
			//如果不存在才新增未校验记录
			if(!diseaseNames.contains(diseaseName)){
				//新增记录
				IcdDiseaseSectionRepository sr = new IcdDiseaseSectionRepository();
				sr.setCheckFlag("0");
				sr.setDiseaseName(diseaseName);
				sr.setModifierId("1");
				StringBuffer externalSection = new StringBuffer();
				externalSection.append(",");
				for(String s:section){
					externalSection.append(s).append(",");
				}
				sr.setExternalSection(externalSection.toString());
				sr.setOptimumSection("");
				icdDiseaseSectionRepositoryDao.insert(sr);
			}
			
			
		}
		return ReturnUtil.success();
	}
    public  void readTxtFile(String filePath){
        try {
                String encoding="UTF-8";
                File file=new File(filePath);
                if(file.isFile() && file.exists()){ //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    while((lineTxt = bufferedReader.readLine()) != null){
                        System.out.println(lineTxt);
                        String[] lineTexts = lineTxt.split("\t");
                        //   疾病    内部科室(不需要保存)   外部科室    最佳科室   
                        String externalSection = lineTexts[2].replace("[", "").replace("]", "").replace("', '", ",").replace("'", ",");
        				IcdDiseaseSectionRepository sr = new IcdDiseaseSectionRepository();
        				sr.setCheckFlag("0");
        				sr.setDiseaseName(lineTexts[0]);
        				sr.setModifierId("1");
        				sr.setExternalSection(externalSection);
        				sr.setCheckFlag("1");
        				if(lineTexts.length>3){
        					sr.setOptimumSection(lineTexts[3]);
        				}else{
        					sr.setOptimumSection("");
        				}
        				icdDiseaseSectionRepositoryDao.insert(sr);
                    }
                    read.close();
        }else{
            System.out.println("找不到指定的文件");
        }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
     
    }
}
